// 编译后脚本
const fsp = require('fs').promises;
const fs = require("fs")
const path = require('path');
const os = require('os')
const child_process = require("child_process");

const cmd = `git rev-list --all --count`

async function childSpawnPromise(command, args) {
  return new Promise((resolve,reject)=>{
    const cmd = child_process.spawn(command, args, { shell: true})
    let datas = ''
    // 为了解决类型问题
    cmd.stdout.on('data', (data) => {
      datas += data
    });

    cmd.on('error', (data) => {
      reject(`执行命令发生错误:err:${data}, command:${command}`)
    });

    cmd.on('exit',(code, err)=>{
      resolve(datas)
    })
  })
}

async function copyDir(src, dest) {
  const entries = await fsp.readdir(src, { withFileTypes: true });

  await fsp.mkdir(dest, { recursive: true });

  for (let entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      await copyDir(srcPath, destPath);
    } else {
      await fsp.copyFile(srcPath, destPath);
    }
  }
}
async function main() {
  console.log("开始执行编译后脚本")
  console.log("自动复制db文件夹")
  await copyDir('./db', './dist_electron/win-unpacked/db')
  console.log("自动复制plugins文件夹")
  await copyDir('./plugins', './dist_electron/win-unpacked/plugins')
  if (os.platform() !== 'darwin') {
    console.log("清理mac下的额外文件")
    // 删除文件
    fs.unlink('./dist_electron/win-unpacked/db/stockfish-macos', (err) => {
      if (err) {
        console.log("err", err)
      }
      console.log('文件已删除');
    });
  }
  // 重命名文件夹
  let title = `Chessmate V`
  let packageJson = fs.readFileSync('./package.json')
  packageJson = JSON.parse(packageJson)
  let version = packageJson.version
  title += version


  const res = await childSpawnPromise(cmd)
  title+=`.${Number(res)}`
  console.log("版本号: ", title)
  console.log("重命名打包后的文件夹")
  try {
    fs.renameSync('./dist_electron/win-unpacked', `./dist_electron/${title}`)
  } catch(err) {
    console.log("err", err)
  }
  
  console.log("编译完成")
}

main()